<template>
  <Grid
    ref="gridRef"
    :fetch-data="fetchData"
    border
    header-align="center"
    align="center"
    height="95%"
    auto-resize
    remote-sort
    seq-serial
    :pager="pagerConfig"
    :edit-config="{ trigger: 'dblclick', mode: 'cell', showStatus: true }"
    @edit-closed="editClosed"
    :edit-rules="validRules"
    :mouse-config="{ selected: true }"
    :keyboard-config="{ isArrow: true, isDel: true, isTab: true }"
    :row-class-name="rowClassName"
    is-before-page-change
    @before-page-change="onBeforePageChange"
    show-footer :footer-method="footerMethod"
  >
    <template #toolbar>
      <GridToolbar setting>
        <template #buttons>
          <div style="display: flex">
            <div style="min-width: 60px;line-height: 28px;margin-left: 10px;">回货日期：</div>
            <DatePicker
              value-format="yyyy-MM-dd"
              clearable
              v-model="dateList"
              class="datePicker"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              range-separator="至"
              :picker-options="pickerOptionsDateRange1"
            ></DatePicker>
            <Select v-model="idc2" placeholder="识别码2" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in idc2Op" :key="item" :label="item" :value="item">
              </Option>
            </Select>
            <Select v-model="supplied" placeholder="供应商" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in suppliedOp" :key="item" :label="item" :value="item">
              </Option>
            </Select>
            <Select v-model="material_category" placeholder="物料品类" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in materialCategoryOp" :key="item" :label="item" :value="item">
              </Option>
            </Select>
          </div>
          <div style="display: flex;justify-content: space-between;">
            <div style="margin: 5px 5px 0 0">
              <Select v-model="material_name" placeholder="物料名称" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in materialNameOp" :key="item" :label="item" :value="item"></Option>
              </Select>
            </div>
            <div style="margin: 5px 5px 0 0">
              <Select v-model="color" placeholder="色号&颜色" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in colorOp" :key="item" :label="item" :value="item"></Option>
              </Select>
            </div>
            <div style="margin: 5px 5px 0 0;display: flex;">
              <Select v-model="specification" placeholder="规格" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in specificationOp" :key="item" :label="item" :value="item"></Option>
              </Select>
            </div>
            <div style="margin: 5px 5px 0 0;display: flex;">
              <Select v-model="work_order_num" placeholder="工单号" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in workOrderNumOp" :key="item" :label="item" :value="item"></Option>
              </Select>
            </div>
            <Button type="primary" style="margin-top: 5px;" @click="handleSearch">查询</Button>
          </div>
          <div style="display: flex;">
            <FileUpload
              :http-request="httpRequest"
              :file-list="fileList"
              accept=".xlsx"
              :show-file-list="false">
              <Button style="margin: 10px 0 0 10px;">导入</Button>
            </FileUpload>
            <Button style="margin: 10px 0 0 10px;" @click="add">新增</Button>
            <Button style="margin: 10px 0 0 10px;" @click="save">保存</Button>
            <Button style="margin: 10px 0 0 10px;" @click="deletes">删除</Button>
            <Button style="margin: 10px 0 0 10px;" @click="exportFile">导出</Button>
          </div>
        </template>
      </GridToolbar>
      <div style="margin-left: 10px;color: #5e7ce0;">
        提示<Activation style="font-size: 14px;margin-bottom: 4px;"></Activation>：
        新增数据，需要点击保存按钮才会生效；若想取消未保存数据，请点击查询按钮刷新表格即可。
      </div>
    </template>
    <GridColumn type="index" width="60" fixed="left"></GridColumn>
    <GridColumn type="selection" width="60"></GridColumn>
    <GridColumn field="row_count_by_idc2" title="识别码2行数统计" min-width="140" show-icon></GridColumn>
    <GridColumn field="idc2" title="识别码2（供应商/物料品类/物料名称/色号&颜色/规格）" min-width="360" show-icon>
      <template #header>
        <div>识别码2</div>
        <div>（供应商/物料品类/物料名称/色号&颜色/规格）</div>
      </template>
    </GridColumn>
    <GridColumn field="work_order_num" title="工单号" min-width="120" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.work_order_num" placeholder="工单号" clearable filterable allow-create is-drop-inherit-width>
          <Option v-for="item in workOrderNumOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="spu" title="款号" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="return_date" title="回货日期" min-width="160" show-icon :editor="{ component: 'input', attrs: { type: 'date' } }" sortable></GridColumn>
    <GridColumn field="store" title="店铺" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="supplied" title="供应商" min-width="120" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.supplied" clearable filterable allow-create>
          <Option v-for="item in suppliedOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="material_category" title="物料品类" min-width="160" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.material_category" clearable filterable allow-create>
          <Option v-for="item in materialCategoryOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="material_num" title="物料编号" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="material_name" title="物料名称" min-width="160" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.material_name" clearable filterable allow-create>
          <Option v-for="item in materialNameOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="color" title="色号&颜色" min-width="160" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.color" placeholder="色号&颜色" clearable filterable allow-create is-drop-inherit-width>
          <Option v-for="item in colorOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="specification" title="规格" min-width="140" show-icon :editor="{}">
      <template #edit="data">
        <Select v-model="data.row.specification" placeholder="规格" clearable filterable allow-create is-drop-inherit-width>
          <Option v-for="item in specificationOp" :key="item" :label="item" :value="item"></Option>
        </Select>
      </template>
    </GridColumn>
    <GridColumn field="delivery_num" title="送货单号" min-width="120"  show-icon :editor="editor"></GridColumn>
    <GridColumn field="count_by_idc2" title="按识别码计入库数量-M/个" min-width="200" show-icon></GridColumn>
    <GridColumn field="inbound_quantity" title="入库数" min-width="120" show-icon></GridColumn>
    <GridColumn field="remarks" title="备注" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="return_month" title="回货月份" min-width="120" show-icon></GridColumn>
    <GridColumn field="material_unit" title="来料单位" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="price" title="单价" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="total_amount_by_idc2" title="按识别码2入库总金额" min-width="180" show-icon></GridColumn>
    <GridColumn field="total_inbound_amount" title="入库总金额" min-width="120" show-icon></GridColumn>
    <GridColumn field="air_gap" title="空差" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="total_material_quantity" title="来料总数" min-width="120" show-icon></GridColumn>
    <GridColumn field="return_detail_count" title="回货细数" min-width="140" show-icon :editor="editor">
      <GridColumn v-for="item in 50" :field="'return_detail_count' + item" :key="item" :title="item+''" min-width="140" show-icon :editor="editor">
        <template #default="data">
          {{ data.row[`return_detail_count${item}`] || '' }}
        </template>
      </GridColumn>
    </GridColumn>
  </Grid>
</template>

<script setup>
import { Grid, GridColumn, GridToolbar, DatePicker, Select, Option, Button, Modal, FileUpload } from '@opentiny/vue'
import { IconActivation } from '@opentiny/vue-icon'
import { ref, onMounted, nextTick } from 'vue'
import { timeFormat, pickerOptionsDateRange1, rowClassName, downLoadExcel } from 'untils'
import {
  getWarehouseAuxiliaryInbound,
  updateWarehouseAuxiliaryInbound,
  addWarehouseAuxiliaryInbound,
  getAuxiliarySupplied,
  getAuxiliaryMaterialCategory,
  getAuxiliaryMaterialName,
  getAuxiliaryIdc2,
  deleteAuxiliaryInbound,
  getAuxiliaryColor,
  getAuxiliarySpecification,
  getAuxiliaryWorkOrderNum,
  downloadAuxiliaryInbound,
  uploadAuxiliaryInbound
 } from '@/request/api'
const Activation = IconActivation()
const gridRef = ref()
const curParams = ref()
const supplied = ref('')
const suppliedOp = ref('')
const idc2 = ref('')
const idc2Op = ref([])
const material_category = ref('')
const materialCategoryOp = ref([])
const material_name = ref('')
const materialNameOp = ref([])
const colorOp = ref([])
const specificationOp = ref([])
const workOrderNumOp = ref([])
const color = ref('')
const work_order_num = ref('')
const specification = ref('')
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 365 * 3)
const dateList = ref([timeFormat(start), timeFormat(end)])
const total_kg = ref()
const validRules = {
  return_date: [{ required: true, message: '必填' }],
  supplied: [{ required: true, message: '必填' }],
  material_category: [{ required: true, message: '必填' }],
  material_name: [{ required: true, message: '必填' }],
  color: [{ required: true, message: '必填' }],
  specification: [{ required: true, message: '必填' }],
  material_unit: [{ required: true, message: '必填' }],
  price: [{ required: true, message: '必填' }],
  return_detail_count: [{ required: true, message: '必填' }]
}
const pagerConfig = ref({
  attrs: {
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100],
    total: 0,
    align: 'left',
    layout: 'total, prev, pager, next, jumper, sizes'
  }
})
const editor = ref({ component: 'input', autoselect: true })
const handleSearch  = () => {
  const insertRecords = gridRef.value.getInsertRecords()
  if (insertRecords.length) {
    Modal.confirm('当前有未保存的数据，您确定要放弃保存吗？').then((res) => {
      if (res === 'confirm') {
        gridRef.value.pagerConfig.currentPage = 1
        gridRef.value.handleFetch()
      }
    })
  } else {
    gridRef.value.pagerConfig.currentPage = 1
    gridRef.value.handleFetch()
  }
}
const handleSearchNoTip  = () => {
  gridRef.value.pagerConfig.currentPage = 1
  gridRef.value.handleFetch()
}
function footerMethod({ columns, data }) {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '汇总'
      }
      if (column.property === 'inbound_quantity') {
        return total_kg.value
      }
      return null
    })
  ]
}
const getData = ({ page, sort }) => {
  const { field, order } = sort || {}
  return new Promise((resolve) => {
    const start_date = dateList.value[0]
    const end_date = dateList.value[1]
    const size = page.pageSize
    const currentPage = page.currentPage
    const params = {
      start_date,
      end_date,
      idc_2: encodeURIComponent(idc2.value),
      supplier: encodeURIComponent(supplied.value),
      category: encodeURIComponent(material_category.value),
      size,
      currentPage,
      name: encodeURIComponent(material_name.value),
      color: encodeURIComponent(color.value),
      specification: encodeURIComponent(specification.value),
      work_order_num: encodeURIComponent(work_order_num.value),
      sort: field || '',
      sort_seq: order || 'asc'
    }
    curParams.value = params
    getWarehouseAuxiliaryInbound(params).then(res => {
      total_kg.value = res.data.total_kg
      if (res?.data?.ret === 0) {
        const result = res.data.result.map(item => {
          for(let i = 1; i < 51; i++) {
            item['return_detail_count'+ i] = item.return_detail_count[i - 1] ||''
          }
          return {
            ...item,
          }
        })
        resolve({
          result: result,
          page: { total: res.data.total }
        })
      } else {
        resolve({
          result: [],
          page: { total: 0 }
        })
      }
    })
  })
}
const editClosed = ({ column, row }) => {
  const field  = column.property
  const title = column.title
  const hasChange = gridRef.value.hasRowChange(row, field)
  if (hasChange) {
    const params = {
      id: row.id
    }
    if (field.includes('return_detail_count')) {
      params.edit_field = 'return_detail_count'
      const list = Object.entries(row).filter(item =>item[0] !== 'return_detail_count' && item[0].includes('return_detail_count') && item[1]).map(item => Number(item[1]))
      params.edit_value = list
    } else {
      params.edit_field = field
      params.edit_value = ['price','air_gap'].includes(field) ? Number(row[field]) : row[field]
    }
    updateWarehouseAuxiliaryInbound(params).then(res => {
      if (res?.data?.ret === 0) {
        Modal.message({ message: '编辑成功', status: 'success' })
        gridRef.value.handleFetch()
      } else {
        Modal.message({ message: res.data.msg, status: 'error' })
      }
    })
  }
}
const add = () => {
  gridRef.value.insert({ unSave: true }).then((res) => {
    gridRef.value.setActiveRow(res.row)
  })
}
const save = () => {
  const insertRecords = gridRef.value.getInsertRecords()
  gridRef.value.validate(insertRecords, valid => {
    if (!valid) {
      return
    }
    if (insertRecords.length) {
      const params = []
      insertRecords.forEach(item => {
        const {
          work_order_num, spu, return_date, store, supplied, material_category, material_num, material_name,
          color, specification, delivery_num, remarks, material_unit, price, air_gap, return_detail_count
        } = item
        const list = Object.entries(item).filter(ite =>ite[0] !== 'return_detail_count' && ite[0].includes('return_detail_count') && ite[1]).map(it => Number(it[1]))
        const obj = {
          work_order_num,
          spu,
          return_date,
          store,
          supplied,
          material_category,
          material_num,
          material_name,
          color,
          specification,
          delivery_num,
          remarks,
          material_unit,
          price: Number(price),
          air_gap: Number(air_gap),
          return_detail_count: list
        }
        params.push(obj)
      })
      addWarehouseAuxiliaryInbound(params).then(res => {
        if (res?.data?.ret === 0) {
          handleSearchNoTip()
          Modal.message({ message: '新增成功', status: 'success' })
        } else {
          Modal.message({ message: res.data.msg, status: 'error' })
        }
      })
    }
  })
}
const deletes = () => {
  const selectRecords = gridRef.value.getSelectRecords()
  if (selectRecords.every(item => item.unSave)) {
    gridRef.value.removeSelecteds()
    return
  }
  if (selectRecords.length) {
    Modal.confirm('确定要删除所选数据吗？').then((res) => {
      if (res === 'confirm') {
        const ids = selectRecords.map(item => item.id).filter(item => item)
        if (ids.length) {
          deleteAuxiliaryInbound({ ids }).then(res => {
            if (res?.data?.ret === 0) {
              handleSearchNoTip()
              Modal.message({ message: '删除成功', status: 'success' })
            } else {
              Modal.message({ message: res.data.msg, status: 'error' })
            }
          })
        }
      }
    })
  } else {
    Modal.alert('请先选择要删除的数据', '提示')
  }
}
const fileList = ref([])
const httpRequest = (files) => {
  const formData = new FormData()
  formData.append('file', files.file)
  uploadAuxiliaryInbound(formData).then(res => {
    if (res?.data?.ret === 0) {
      handleSearchNoTip()
      Modal.message({ message: '成功导入辅料入库记录', status: 'success' })
    } else {
      Modal.message({ message: res.data.msg, status: 'error' })
    }
  }).catch(() => {
    Modal.message({ message: res.data.msg, status: 'error' })
  })
}
const exportFile = () => {
  const params = {
    ...curParams.value 
  }
  downloadAuxiliaryInbound(params).then(res => {
    downLoadExcel(res)
  })
}
function onBeforePageChange(params) {
  const insertRecords = gridRef.value.getInsertRecords()
  const { callback, rollback } = params
  if (insertRecords.length) {
    Modal.confirm('当前有未保存的数据，您确定要放弃保存吗？').then((res) => {
      if (res === 'confirm') {
        callback && callback()
      } else {
        rollback && rollback()
      }
    })
  } else {
    callback && callback()
  }
}
const fetchData = {
  api: getData
}
const getInitData = () => {
  getAuxiliarySupplied().then(res => {
    if (res?.data?.ret === 0) {
      suppliedOp.value = res.data.result
    }
  })
  getAuxiliaryIdc2().then(res => {
    if (res?.data?.ret === 0) {
      idc2Op.value = res.data.result
    }
  })
  getAuxiliaryMaterialCategory().then(res => {
    if (res?.data?.ret === 0) {
      materialCategoryOp.value = res.data.result
    }
  })
  getAuxiliaryMaterialName().then(res => {
    if (res?.data?.ret === 0) {
      materialNameOp.value = res.data.result
    }
  })
  getAuxiliaryColor().then(res => {
    if (res?.data?.ret === 0) {
      colorOp.value = res.data.result
    }
  })
  getAuxiliarySpecification().then(res => {
    if (res?.data?.ret === 0) {
      specificationOp.value = res.data.result
    }
  })
  getAuxiliaryWorkOrderNum().then(res => {
    if (res?.data?.ret === 0) {
      workOrderNumOp.value = res.data.result
    }
  })
}
onMounted(() => {
  nextTick(() => {
    getInitData()
  })
})
</script>
<style lang="scss" scoped>
.tiny-select {
  width: inherit;
  margin-left: 5px;
}
:deep(.tiny-date-editor.tiny-range-editor.tiny-input.tiny-input__inner.tiny-date-editor--daterange) {
  width: 280px;
}
:deep(.tiny-grid-toolbar) {
  padding: 12px 0 0 0;
}
:deep(.tiny-grid-toolbar .tiny-grid-custom__wrapper) {
  top: 75px;
}
</style>